
define(['jquery'], () => {
    class Carousel {
        constructor(selectorNode) {
            this.$ban = $(selectorNode),
            this.$ol = $('#car_list'),
            this.$next = $('#next'),
            this.$prev = $('#prev'),
            this.lastindex = 0,
            this.index = 0,
            this.timer = null
            this.init()
        }
        //初始ol里li个数
        init() {
            this.$a = this.$ban.children('a')
            this.len = this.$a.length
            for(var i = 0; i < this.len; i++) {
                if(i === 0) {
                    $('<li>').addClass('ac').attr('ol-index', i + 1).appendTo(this.$ol)
                } else {
                    $('<li>').attr('ol-index', i + 1).appendTo(this.$ol)
                }
            }
            this.$li = this.$ol.children('li')
            this.ol_jump()
            this.inner()
            this.next()
            this.prev()
        }
        
        //向下翻页
        next() {
            this.$next.on('click', () => {
                this.lastindex = this.index;
                this.index++;
                this.index = this.index > (this.len - 1) ? 0 : this.index;
                this.$li.eq(this.lastindex).removeClass('ac');
                this.$li.eq(this.index).addClass('ac');
                this.$a.eq(this.index).css({opacity:'1'})
                this.$a.eq(this.lastindex).css({opacity:'0'})
                
            })
        }

        //上一页
        prev() {
            this.$prev.on('click', () => {
                this.lastindex = this.index;
                this.index--;
                this.index = this.index < 0 ? (this.len -1) : this.index;
                this.$li.eq(this.lastindex).removeClass('ac');
                this.$li.eq(this.index).addClass('ac');
                this.$a.eq(this.index).css({opacity:'1'})
                this.$a.eq(this.lastindex).css({opacity:'0'})
                
            })
        }

        //点击ol直接跳转
        ol_jump() {
            this.$li.on('click', function(item) {
                this.lastindex = this.index
                this.index = parseInt($(this).attr('ol-index'))
                this.$li.eq(this.lastindex).removeClass('ac');
                this.$li.eq(this.index).addClass('ac');
                this.$a.eq(this.index).css({opacity:'1'})
                this.$a.eq(this.lastindex).css({opacity:'0'})
            })
                
        }
        inner() {
            let _this = this
            $('.carousel').hover(function () {
                clearInterval(_this.timer)
              }, (function auto () {
                _this.timer = setInterval(() => {
                  $('#next').trigger('click')
                }, 3000)
                return auto
              })())
            
        }
    }
    return new Carousel('#carousel');
});